package com.web.util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class JDBCUtils {
    public static int update(String sql, Object... args) {
        try (Connection connection = DataSourceUtils.getConnection()) {
            PreparedStatement ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            int rows = ps.executeUpdate();
            return rows;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> query(Class<T> clazz, String sql, Object... args) {
        try (Connection connection = DataSourceUtils.getConnection()) {
            PreparedStatement ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            List<T> list = new ArrayList<>();
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                T t = clazz.newInstance();
                Field[] fields = clazz.getDeclaredFields();
                for (Field field : fields) {
                    Object value = rs.getObject(field.getName());
                    field.setAccessible(true);
                    field.set(t, value);
                }
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            throw new RuntimeException("数据库查询失败: " + e.getMessage(), e);
        }
    }
}